#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright 2013 Antoine Drouin (poinix@gmail.com)
#
# This file is part of PAT.
#
#    PAT is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    PAT is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with PAT.  If not, see <http://www.gnu.org/licenses/>.
#

"""
 State feedback with pole placemement for the planar VTOL
"""

import numpy as np
import matplotlib.pyplot as plt
import control.matlab

np.set_printoptions(precision=2, suppress=False, linewidth=160)

import pat.vehicles.rotorcraft.dynamic_model_planar_simple as dm
import pat.utils as pu

my_dm = dm.DynamicModel()
Xe, Ue = my_dm.trim()

A, B = my_dm.jacobian(Xe, Ue)
wol, Mol = np.linalg.eig(A)
cl_poles = [-4, -4, -2, -2, -1, -1]
K = control.matlab.place(A, B, cl_poles)
Acl = A-np.dot(B, K)
wcl, Mcl = np.linalg.eig(Acl)

dt = 0.01; time = np.arange(0., 15., dt)
X = np.zeros((len(time), dm.sv_size))
X0 = np.array(Xe); X0[my_dm.sv_x]+=1; X0[my_dm.sv_z]+=1; 
my_dm.reset(X0)
X[0] = my_dm.X
U = np.zeros((len(time), dm.iv_size))

for i in range(1,len(time)):
    U[i-1] = Ue - np.dot(K, X[i-1]-Xe)
    X[i] = my_dm.run(dt, U[i-1])

U[-1] = U[-2]

my_dm.plot_state(time, X, U,  window_title="Pole placement on Planar VTOL")

text1 = '''
A
{:s}
'''.format(A)
text2 = '''
B
{:s}
'''.format(B)
text3 = '''
Open loop poles : {:s}
'''.format(wol)
text4 = '''
Gain :
{:s}
Closed loop poles : {:s}
Closed loop eigenvectors:
{:s}
'''.format(K, wcl, Mcl)
pu.write_text(3, 3, 8, (text1, text2, text3, text4), colspan=2, loc=[[0.1, 9.7],[2.9, 9.7],[0.1, 3.], [4.9, 9.7]],
              filename="../doc/images/wiki/planar_vtol_state_feedback_2.png")
plt.show()
